package net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 * Fetch captcha challenges and then the corresponding images.
 * @author Brian
 */
public class CaptchaFetcher {
	public class ChallengeNotFoundError extends Exception {}

	/** Challenges are generated by reading the JSON response from the ReCaptcha challenge-generator. */
	private final URL challengeURL;

	/**
	 * Create a captcha challenge and challenge data (image) fetcher
	 * given a board URL that has a captcha on it.
	 * @param pageOnBoard URL which must have a ReCaptcha field
	 * @throws IOException 
	 * @throws ChallengeNotFoundError 
	 */
	public CaptchaFetcher(URL pageOnBoard) throws IOException, ChallengeNotFoundError {
		/* Example:
	<script type="text/javascript"
	   src="http://api.recaptcha.net/challenge?k=6Ldp2bsSAAAAAAJ5uyx_lx34lJeEpTLVkP5k04qc"> 
	</script> 
		 */
		Pattern challengeRegex = Pattern.compile("src=\"(http://api\\.recaptcha\\.net/challenge\\?k=[^\"]+)\"");
		BufferedReader pageReader = new BufferedReader(new StringReader(PageCache.fetch(pageOnBoard)));
		String line;
		while ((line = pageReader.readLine()) != null) {
			Matcher m = challengeRegex.matcher(line);
			if (m.find()) {
				challengeURL = new URL(m.group(1));
				return;
			}
		}
		throw new ChallengeNotFoundError();
	}
	
	public ImageCaptcha getImageChallenge() throws IOException, ChallengeNotFoundError {
		URLConnection captchaJSON = challengeURL.openConnection();
		/* Example:
var RecaptchaState = {
    site : '6Ldp2bsSAAAAAAJ5uyx_lx34lJeEpTLVkP5k04qc',
    challenge : '03AHJ_VutlD4S2slj6fwBclT6VibXHU1kYwkZj_icyUBkOvltUgqKrDNQOHRKn28PTCseIvxsNpRmFmyMZu_GoxTVKR-1GYi4ObpTstq4hN1kv-RzvovaGIv9kF7g08D5P4bmDDOfLm1LT7DNVlqj1LndDHBaXJs2DOQ',
    is_incorrect : false,
    programming_error : '',
    error_message : '',
    server : 'http://www.google.com/recaptcha/api/',
    timeout : 18000
};

document.write('<scr'+'ipt type="text/javascript" s'+'rc="' + RecaptchaState.server + 'js/recaptcha.js"></scr'+'ipt>');
		 */
		BufferedReader pageReader = new BufferedReader(new InputStreamReader(captchaJSON.getInputStream()));
		Pattern challengeRegex = Pattern.compile("\\s*challenge\\s*:\\s*'([^']+)'");
		String line;
		while ((line = pageReader.readLine()) != null) {
			Matcher m = challengeRegex.matcher(line);
			if (m.lookingAt()) {
				URL imageURL = new URL("http://www.google.com/recaptcha/api/image?c=" + m.group(1));
				return new ImageCaptcha(m.group(1), imageURL);
			}
		}
		throw new ChallengeNotFoundError();
	}
	
	public static void main(String args[]) throws Exception {
		CaptchaFetcher cf = new CaptchaFetcher(new URL("http://boards.4chan.org/a/"));
		ImageCaptcha captcha = cf.getImageChallenge();
		JFrame display = new JFrame();
		display.setContentPane(new JLabel(captcha.getIcon()));
		display.setVisible(true);
	}
}
